<template>
  <div class="source-management" style="width: 2000px;">
    <!-- 顶部操作栏 -->
    <div class="toolbar">
      <el-button type="primary" icon="el-icon-plus" @click="onAdd">新增</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="onBatchDelete">批量删除</el-button>
      <el-button icon="el-icon-refresh" @click="onRefresh" circle style="margin-left:auto" />
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 2000px; margin-top: 8px" @selection-change="handleSelectionChange"
      height="600">
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="sName" label="商品名称" width="150">
        <template #header>
          <div>商品名称</div>
          <el-input size="small" placeholder="输入进行查询" v-model="filters.SName" @input="onFilter"
            @keyup.enter="ShowSource" />
        </template>
      </el-table-column>
      <el-table-column prop="batch" label="生产批次" width="150">
        <template #header>
          <div>生产批次</div>
          <el-input size="small" placeholder="输入进行查询" v-model="filters.Batch" @input="onFilter"
            @keyup.enter="ShowSource" />
        </template>
      </el-table-column>
      <el-table-column prop="expiration_date" label="保质期（天）" width="150">
        <template #header>
          <div>保质期（天）</div>
          <el-input size="small" placeholder="输入进行查询" v-model="filters.Expiration_date" @input="onFilter"
            @keyup.enter="ShowSource" />
        </template>
      </el-table-column>
      <el-table-column prop="production_License" label="生产许可证号" width="150">
        <template #header>
          <div>生产许可证号</div>
          <el-input size="small" placeholder="输入进行查询" v-model="filters.Production_License" @input="onFilter"
            @keyup.enter="ShowSource" />
        </template>
      </el-table-column>
      <el-table-column prop="manufacturing_Enterprises" label="生产企业" width="150">
        <template #header>
          <div>生产企业</div>
          <el-input size="small" placeholder="输入进行查询" v-model="filters.manufacturing_Enterprises" @input="onFilter"
            @keyup.enter="ShowSource" />
        </template>
      </el-table-column>
      <el-table-column prop="nformation_Completeness" label="信息完整度" width="150">
        <template #default="scope">
          <span
            :style="{ color: scope.row.nformation_Completeness < 100 ? 'red' : (scope.row.nformation_Completeness < 100 ? '#e6a23c' : 'green'), fontWeight: 'bold' }">
            {{ scope.row.nformation_Completeness }}%
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="createUserId" label="创建人" width="150">
        <template #header>
          <div>创建人</div>
          <el-input size="small" placeholder="输入进行查询" v-model="filters.CreateUserId" @input="onFilter"
            @keyup.enter="ShowSource" />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="150">
        <template #header>
          <div>创建时间</div>
          <el-input size="small" placeholder="输入进行查询" v-model="filters.CreateTime" @input="onFilter"
            @keyup.enter="ShowSource" />
        </template>
      </el-table-column>
      <el-table-column prop="upDataUserId" label="修改人" width="150">
        <template #header>
          <div>修改人</div>
          <el-input size="small" placeholder="输入进行查询" v-model="filters.UpDataUserId" @input="onFilter"
            @keyup.enter="ShowSource" />
        </template>
      </el-table-column>
      <el-table-column prop="upDataTime" label="修改时间" width="150">
        <template #header>
          <div>修改时间</div>
          <el-input size="small" placeholder="输入进行查询" v-model="filters.UpDataTime" @input="onFilter"
            @keyup.enter="ShowSource" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-link type="primary" @click="onDetail(scope.row)">详情</el-link>
          <el-link type="primary" @click="onEdit(scope.row)">修改</el-link>
          <el-link type="primary" @click="onExport(scope.row)">导出溯源码</el-link>
          <el-link type="danger" plain @click="onDelete(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="PageDate.PageIndex" v-model:page-size="PageDate.PageSize"
        :page-sizes="[15, 20, 25, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
        :total="PageDate.count" prev-text="上一页" next-text="下一页" />
    </div>

    <!-- 添加/编辑弹窗表单 -->
    <SourceFormDialog ref="formDialogRef" @refresh="ShowSource" />

    <!-- 删除确认弹窗（自定义el-dialog，逻辑由你实现） -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="400px">
      <div>确认删除已选的{{ selectedRows.length }}个溯源商品？</div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="onConfirmBatchDelete">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { source } from '@/http/axiosHelper'
import SourceFormDialog from './SourceFormDialog.vue'
import moment from 'moment'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
const tableData = ref([])
const formDialogRef = ref()

function ShowSource() {
  source.get("/api/Management/TracebackQuery", {
    params: {
      PageIndex: PageDate.value.PageIndex,
      PageSize: PageDate.value.PageSize,
      CreateUserId: filters.CreateUserId,
      CreateTime: filters.CreateTime,
      UpDataUserId: filters.UpDataUserId,
      UpDataTime: filters.UpDataTime,
      SName: filters.SName,
      Batch: filters.Batch,
      Expiration_date: filters.Expiration_date,
      Production_License: filters.Production_License,
      manufacturing_Enterprises: filters.manufacturing_Enterprises
    }
  }).then((res) => {
    console.log(res.data.pageData);

    tableData.value = res.data.pageData;
    tableData.value.forEach((item: any) => {
      item.createTime = moment(item.createTime).format("YYYY-MM-DD HH:mm:ss")
      item.upDataTime = item.upDataTime ? moment(item.upDataTime).format("YYYY-MM-DD HH:mm:ss") : null
    })
    PageDate.value.count = res.data.count;
  })
}

// filters 字段以用户自定义为准
const filters = reactive({
  CreateUserId: '',
  CreateTime: '',
  UpDataUserId: '',
  UpDataTime: '',
  SName: '',
  Batch: '',
  Expiration_date: '',
  Production_License: '',
  manufacturing_Enterprises: ''
})


const selectedRows = ref<number[]>([])
const deleteDialogVisible = ref(false)

function onBatchDelete() {
  // TODO: 批量删除逻辑由你实现
  deleteDialogVisible.value = true
}

function onRefresh() {
  ShowSource();
}
function onConfirmBatchDelete() {


  console.log(selectedRows.value);

  if (selectedRows.value.length == 0) {
    ElMessage.warning("至少选择一个");
    return;
  }
  // 批量删除确认逻辑，POST方式，body为数组
  source.post("/api/Management/TracebackListDelete", selectedRows.value)
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        deleteDialogVisible.value = false
        ShowSource();
      }
      else {
        ElMessage.error(res.data.msg);
      }
    })

}
function handleSelectionChange(val: any[]) {
  // 只收集所有选中项的id
  selectedRows.value = val.map(item => item.id)
  // TODO: 处理多选逻辑
}



function onFilter() {
  // 这里只做静态演示，实际应根据 filters 过滤 tableData
}

function onDetail(row: any) {
  router.push({ path: '/TraceDetailView', query: { id: row.id } })
}
function onEdit(row: any) {
  formDialogRef.value.open(row, '编辑')
}
function onExport(row: any) { }
function onDelete(row: any) {
  ElMessageBox.confirm(
    '确认删除该溯源商品?',
    '删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      source.post("/api/Management/TracebackDelete", null,
        {
          params: {
            Id: row.id
          }
        })
        .then((res) => {
          if (res.data.code == 200) {
            ShowSource();
            ElMessage.success(res.data.msg)
          }
          else {
            ElMessage.error(res.data.msg)
          }
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '确认取消',
      })
    })

}

function onAdd() {
  formDialogRef.value.open(null, '添加')
  ShowSource();
}

const PageDate = ref({
  PageIndex: 1,
  PageSize: 15,
  count: 0,
})

watch(() => { PageDate.value.PageIndex, PageDate.value.PageSize }, () => {
  ShowSource()
}, { deep: true })

onMounted(() => {
  ShowSource()
})
</script>

<style scoped>
.source-management {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
}

.toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
}

.pagination-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 16px;
}

.total-text {
  margin-left: 16px;
  color: #888;
}
</style>